package com.VitalFit.config;

import com.VitalFit.exception.FitnessPlanException;
import com.VitalFit.exception.UserAlreadyExistsException;
import com.VitalFit.exception.UserNotFoundException;
import com.VitalFit.exception.WrongPasswordException;
import com.VitalFit.model.enums.ResultEnum;
import com.VitalFit.model.vo.ResultVO;
import com.VitalFit.util.ResultVOUtil;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(UserAlreadyExistsException.class)
    @ResponseBody
    public ResultVO<String> handleUserAlreadyExistsException(UserAlreadyExistsException e) {
        return ResultVOUtil.buildResult(ResultEnum.REGISTER_FAILURE, e.getMessage());
    }

    @ExceptionHandler(UserNotFoundException.class)
    @ResponseBody
    public ResultVO<String> handleUserNotFoundException(UserNotFoundException e) {
        return ResultVOUtil.buildResult(ResultEnum.LOGIN_FAILURE, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultVO<List<String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        // 处理验证异常，例如收集错误信息并返回给客户端
        BindingResult result = ex.getBindingResult();
        List<String> errors = result.getFieldErrors().stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .collect(Collectors.toList());
        return ResultVOUtil.buildResult(ResultEnum.NOT_FOUND,errors);
    }

    @ExceptionHandler(FitnessPlanException.class)
    @ResponseBody
    public ResultVO<String> handleFitnessPlanException(FitnessPlanException e) {
        return ResultVOUtil.buildResult(ResultEnum.PURCHASE_FAILURE, e.getMessage());
    }
    @ExceptionHandler(WrongPasswordException.class)
    @ResponseBody
    public ResultVO<String> handleWrongPasswordException(WrongPasswordException e) {
        return ResultVOUtil.buildResult(ResultEnum.LOGIN_FAILURE, e.getMessage());
    }




    // 可以添加更多的@ExceptionHandler方法来处理其他类型的异常
}